import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Select } from 'antd';
import { EditOutlined, PlusOutlined } from '@ant-design/icons';
import { getUserList, updateUser, getDepartmentList, addUser } from '../../../services/api';
import UserFilter from '../../Filter/userFilter';

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [filteredUsers, setFilteredUsers] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingUser, setEditingUser] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 8,
    total: 0,
  });

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await getUserList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setUsers(response.data);
        setFilteredUsers(response.data);
        setPagination(prev => ({
          ...prev,
          total: response.data.length
        }));
      } else {
        setUsers([]);
        setFilteredUsers([]);
        setPagination(prev => ({
          ...prev,
          total: 0
        }));
        message.error(response.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败');
      setUsers([]);
      setFilteredUsers([]);
      setPagination(prev => ({
        ...prev,
        total: 0
      }));
    }
    setLoading(false);
  };

  const fetchDepartments = async () => {
    try {
      const response = await getDepartmentList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setDepartments(response.data);
      } else {
        setDepartments([]);
        message.error(response.message || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
      setDepartments([]);
    }
  };

  useEffect(() => {
    fetchUsers();
    fetchDepartments();
  }, []);

  const handleFilterChange = (filters) => {
    let result = [...users];
    
    if (filters.depId) {
      result = result.filter(user => user.depId === filters.depId);
    }
    
    if (filters.admin) {
      result = result.filter(user => user.admin === filters.admin);
    }
    
    setFilteredUsers(result);
    setPagination(prev => ({
      ...prev,
      current: 1,
      total: result.length
    }));
  };

  const handleAdd = () => {
    setEditingUser(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingUser(record);
    form.setFieldsValue({
      uId: record.uId,
      uName: record.uName,
      depId: record.depId,
      admin: record.admin,
      password: record.password
    });
    setModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingUser) {
        // 更新用户
        const updateData = {
          uid: parseInt(editingUser.uId, 10),
          uname: values.uName || '',
          depId: values.depId || '',
          admin: values.admin || 'no',
          password: values.password || ''
        };

        const response = await updateUser(updateData);
        if (response.code === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchUsers();
        } else {
          message.error(response.message || '更新失败');
        }
      } else {
        // 新增用户
        const addData = {
          uid: values.uId,
          uname: values.uName,
          depId: values.depId,
          admin: values.admin,
          password: values.password
        };

        const response = await addUser(addData);
        if (response.code === 200) {
          message.success('添加成功');
          setModalVisible(false);
          fetchUsers();
        } else {
          message.error(response.message || '添加失败');
        }
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败: ' + (error.message || '未知错误'));
    }
  };

  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
  };

  const columns = [
    {
      title: '用户ID',
      dataIndex: 'uId',
      key: 'uId',
    },
    {
      title: '用户名',
      dataIndex: 'uName',
      key: 'uName',
    },
    {
      title: '所属部门',
      dataIndex: 'depId',
      key: 'depId',
      render: (depId) => departments.find(d => d.depId === depId)?.depName || depId,
    },
    {
      title: '管理员',
      dataIndex: 'admin',
      key: 'admin',
      render: (admin) => admin === 'yes' ? '是' : '否',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="primary"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
      ),
    },
  ];

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '20px' }}>
      {/* 背景图片层 */}
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: 'url(/assets/house.jpg)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        opacity: 0.8,
        zIndex: 0,
        pointerEvents: 'none'
      }} />

      {/* 内容层 */}
      <div style={{ 
        position: 'relative', 
        zIndex: 1,
        background: 'rgba(255, 255, 255, 0.9)',
        padding: '24px',
        borderRadius: '12px',
        boxShadow: '0 2px 12px rgba(0,0,0,0.1)'
      }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: '24px'
        }}>
          <h2 style={{ margin: 0 }}>用户管理</h2>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加用户
          </Button>
        </div>

        <UserFilter 
          departments={departments}
          onFilterChange={handleFilterChange}
        />

        <Table
          columns={columns}
          dataSource={filteredUsers}
          loading={loading}
          rowKey="uId"
          pagination={pagination}
          onChange={handleTableChange}
          style={{ 
            background: 'white',
            borderRadius: '8px',
            overflow: 'hidden'
          }}
        />
      </div>

      <Modal
        title={editingUser ? '编辑用户' : '添加用户'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="uId"
            label="用户ID"
            rules={[{ required: true, message: '请输入用户ID' }]}
          >
            <Input disabled={!!editingUser} />
          </Form.Item>
          <Form.Item
            name="uName"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="depId"
            label="所属部门"
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <Select>
              {departments.map(dept => (
                <Select.Option key={dept.depId} value={dept.depId}>
                  {dept.depName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="admin"
            label="管理员"
            rules={[{ required: true, message: '请选择是否为管理员' }]}
          >
            <Select>
              <Select.Option value="yes">是</Select.Option>
              <Select.Option value="no">否</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserList; 